package session

import (
	"encoding/json"
	"fmt"

	"easy-sys/logger"
	"easy-sys/sys/domain/menu"
	"easy-sys/sys/domain/user"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

// UserInfoToContext session 中间件，将session中的信息重新设置到上下文
func UserInfoToContext() gin.HandlerFunc {
	return func(c *gin.Context) {
		session1 := sessions.Default(c)
		logger.Debug("设置user", session1.Get("userInfo"))
		var sessionUser = &user.SysUser{}
		if session1.Get("userInfo") != nil {
			json.Unmarshal([]byte(session1.Get("userInfo").(string)), &sessionUser)
		} else {
			var v, isExist = c.Get("userId")
			if isExist {
				var u = user.SysUser{}
				u.UserId = v.(uint64)
				u = user.FindOneByUser(u)
				sessionUser.Name = u.UserName
				sessionUser.Avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"
				sessionUser.MenuList = menu.GetUserMenu(u.UserId)
				sessionUser.Permissions = menu.GetUserPermission(u.UserId)
				data, _ := json.Marshal(sessionUser)
				session1.Set("userInfo", string(data)) // session 使用string存储
				session1.Save()
			} else {
				fmt.Println("不存在用户ID：")
			}
		}
		c.Set("userInfo", sessionUser)
	}
}
